package org.hs.phd.common.simpleplayer.frameviewer;

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;

import org.hs.phd.common.simpleplayer.FramePlayer;
import org.hs.phd.common.simpleplayer.PlayerEvent;
import org.hs.phd.common.simpleplayer.PlayerListener;

public class DefaultController {

	private final FramePlayer player;

	private JButton btnPlayPause;
	private JButton btnPrev;
	private JButton btnNext;
	private JButton btnZoomIn;
	private JButton btnZoomOut;

	private JPanel pnlButtons;

	public DefaultController(FramePlayer player) {
		this.player = player;
		contstructGUI();
	}

	private void contstructGUI() {
		pnlButtons = new JPanel( new FlowLayout(FlowLayout.LEFT) );
		pnlButtons.setBorder( BorderFactory.createEtchedBorder());
		
		btnPlayPause = new JButton("Play/Pause");
		btnPrev = new JButton("Prev");
		btnNext = new JButton("Next");
		btnZoomIn = new JButton("+");
		btnZoomOut = new JButton("-");

		btnPlayPause.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				tooglePause();
			}
		});

		btnPrev.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				player.stepPrevious();
			}
		});

		btnNext.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				player.stepNext();
			}
		});

		btnZoomIn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				player.getViewerController().zoomIn();
			}
		});

		btnZoomOut.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				player.getViewerController().zoomOut();
			}
		});

		
		pnlButtons.add(btnPrev);
		pnlButtons.add(btnNext);
		pnlButtons.add(btnPlayPause);
		pnlButtons.add(btnZoomIn);
		pnlButtons.add(btnZoomOut);
		
		player.addEventListener(new PlayerListener() {
			
			@Override
			public void playerEventOccurred(PlayerEvent event) {
				updateButtonStates();
			}
		});
		
		updateButtonStates();
	}
	
	private void tooglePause() {
		if( player.isPaused() ){
			player.play();
		}else{
			player.pause();
		}
	}

	private void updateButtonStates() {
		boolean paused = player.isPaused();
		btnPrev.setEnabled(paused);
		btnNext.setEnabled(paused);
		btnPlayPause.setText(paused ? "Play" : "Pause");
	}


	public Component getUI() {
		return pnlButtons;
	}

}
